// Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/test/scoped_feature_list.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "content/public/test/browser_test.h"
#include "extensions/common/extension_features.h"
#include "extensions/test/extension_test_message_listener.h"
#include "extensions/test/result_catcher.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace extensions {

enum class AllowWasmInMV3 {
  kTrue,
  kFalse,
};

// Tests web assembly usage in Manifest V3 extensions and its interaction with
// the default extension CSP.
class WasmMV3BrowserTest
    : public ExtensionApiTest,
      public ::testing::WithParamInterface<AllowWasmInMV3> {
 public:
  WasmMV3BrowserTest() {
    std::vector<base::Feature> enabled_features, disabled_features;
    switch (GetParam()) {
      case AllowWasmInMV3::kTrue:
        custom_arg_ = "expect-wasm-allowed";
        enabled_features.push_back(extensions_features::kAllowWasmInMV3);
        break;

      case AllowWasmInMV3::kFalse:
        custom_arg_ = "expect-wasm-disallowed";
        disabled_features.push_back(extensions_features::kAllowWasmInMV3);
        break;
    }

    feature_list_.InitWithFeatures(enabled_features, disabled_features);
  }

  void SetUpOnMainThread() override {
    ExtensionApiTest::SetUpOnMainThread();
    SetCustomArg(custom_arg_);
  }

 private:
  base::test::ScopedFeatureList feature_list_;
  std::string custom_arg_;
};

// Test web assembly usage in a service worker.
IN_PROC_BROWSER_TEST_P(WasmMV3BrowserTest, ServiceWorker) {
  ResultCatcher catcher;

  ExtensionTestMessageListener listener("ready", true);
  ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("wasm_mv3")));
  ASSERT_TRUE(listener.WaitUntilSatisfied());
  listener.Reply("go");

  ASSERT_TRUE(catcher.GetNextResult()) << catcher.message();
}

// Test web assembly usage in an extension page.
IN_PROC_BROWSER_TEST_P(WasmMV3BrowserTest, ExtensionPage) {
  ASSERT_TRUE(RunExtensionTest("wasm_mv3", {.page_url = "page.html"}))
      << message_;
}

INSTANTIATE_TEST_SUITE_P(,
                         WasmMV3BrowserTest,
                         ::testing::Values(AllowWasmInMV3::kTrue,
                                           AllowWasmInMV3::kFalse));

}  // namespace extensions
